package dao

import (
	"fitness/internal/entity/system"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type SysUserRolesDao struct {
	DB     *gorm.DB
	Logger *zap.Logger
}

func NewSysUserRolesDao(db *gorm.DB, logger *zap.Logger) *SysUserRolesDao {
	return &SysUserRolesDao{
		DB:     db,
		Logger: logger,
	}
}
func (sysUserRolesDao *SysUserRolesDao) getGDB() *gorm.DB {
	return sysUserRolesDao.DB
}

// 根据用户id查询角色信息
func (sysUserRolesDao *SysUserRolesDao) FindRoleByUserId(userId any) []system.SysUserRole {
	var uRole []system.SysUserRole
	sysUserRolesDao.getGDB().Where("user_id = ?", userId).Find(&uRole)
	return uRole
}

func (sysUserRolesDao *SysUserRolesDao) FindRolesByUserId(userId uint64) []system.SysUserRole {
	var userRoles []system.SysUserRole
	sysUserRolesDao.getGDB().Where("user_id = ?", userId).Find(&userRoles)
	return userRoles
}

// 保存用户角色
func (sysUserRolesDao *SysUserRolesDao) saveUserRoles(tx *gorm.DB, userId *uint64, roleIds []*uint64) error {
	//先删除已有数据
	err := tx.Delete(&system.SysUserRole{}, "user_id = ?", userId).Error
	if err != nil {
		return err
	}
	//再保存新数据
	var userRoles []system.SysUserRole
	for _, roleId := range roleIds {
		uRole := system.SysUserRole{
			UserId: userId,
			RoleId: roleId,
		}
		userRoles = append(userRoles, uRole)
	}
	tx.CreateInBatches(&userRoles, 10)
	return nil
}

// 根据用户删除角色
func (sysUserRolesDao *SysUserRolesDao) DeleteRoleByUserId(userId any) {
	sysUserRolesDao.getGDB().Where("user_id = ?", userId).Delete(system.SysUserRole{})
}

// 查找对应的角色id是否被应用
func (sysUserRolesDao *SysUserRolesDao) HasAssignedUsers(roleId uint64) (bool, error) {
	var count int64
	sql := `SELECT
            count(*)
        FROM
            sys_user_role t1
            INNER JOIN sys_role t2 ON t1.role_id = t2.id AND t2.is_deleted = 0
            INNER JOIN sys_user t3 ON t1.user_id = t3.id
            AND t3.is_deleted = 0
        WHERE
            t1.role_id = ?`
	err := sysUserRolesDao.getGDB().Raw(sql, roleId).Count(&count).Error
	if err != nil {
		return false, err
	}
	return count > 0, nil
}
